<template>
  <div class="edit-container-col" v-if="dialogShow">
    <SetDesignDialog :title="'编辑'+ name " :dialogVisible="dialogShow" :close="close" :saveclose="saveclose"
      :hasfooter="hasfooter" ref="settingDialog">
      <div class="edit-container-u">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="整体设置" name="1">
            <div class="grid-content bg-purple">
              <div>
                <el-form :model="data">
                  <el-form-item label="选择栅格类型" :label-width="formLabelWidth" style="margin-bottom: 0px;">
                    <el-radio-group v-model="data.type" class="radio-disblock">
                      <el-radio size="mini" label="col-sm">768px及以下（手机竖屏）换行</el-radio>
                      <el-radio size="mini" label="col-md">992px及以下（手机横屏）换行</el-radio>
                      <el-radio size="mini" label="col-lg">1200px及以下（ipad）换行</el-radio>
                      <el-radio size="mini" label="col-xs">不换行</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item v-show="data.type !== 'col-xs'" label="换行上下顺序" :label-width="formLabelWidth"
                    style="margin-bottom: 0px;">
                    <el-select v-model="data.wapfloat" size="mini" placeholder="请选择" style="width: 160px;">
                      <el-option :label="'左上右下'" :value="1"></el-option>
                      <el-option :label="'右上左下'" :value="2"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
                <el-form>
                  <el-form-item label="左右容器颠倒" :label-width="formLabelWidth" style="margin-bottom: 0px;">
                    <el-select v-model="data.reversed" size="mini" placeholder="请选择" style="width: 100px;">
                      <el-option :label="'正常'" :value="0"></el-option>
                      <el-option :label="'颠倒'" :value="1"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
              <div>
                <el-row>
                  <el-divider content-position="left">内间距</el-divider>
                  <el-col :span="12">
                    <div class="grid-content bg-purple">
                       <PaddingTop :title="'顶部内间距'" :defValue="data.row.config.paddingTop" :chgValue="(d)=>{data.row.config.paddingTop = d}" />
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="grid-content bg-purple">
                      <PaddingBottom :title="'底部内间距'" :defValue="data.row.config.paddingBottom" :chgValue="(d)=>{data.row.config.paddingBottom = d}" />
                    </div>
                  </el-col>
                </el-row>
              </div>
              <div>
                <el-row>
                  <el-divider content-position="left">列宽设置</el-divider>
                  <div class="col-opt">
                    <el-link type="primary" @click.stop="argev">平均分配</el-link>
                  </div>
                  <el-col :span="24">
                    <div class="grid-content bg-purple">
                      <el-divider>
                        总宽度：{{total}}
                        &nbsp;&nbsp;&nbsp;&nbsp;剩余：{{10000 - total > 0 ? 10000 - total : 0}}
                        &nbsp;&nbsp;&nbsp;&nbsp;超出：<span class="red">{{total - 10000 > 0 ? total - 10000 : 0}}</span>
                      </el-divider>
                      <div class="boxs">
                        <div class="item" v-for="(cl, index) in data.row.col" :key="index"
                          :style="'width:' + cl.config.width">
                          <WDialogMoveLine v-if="index !== 0" :moving="moving" :stepOffset="stepOffset"
                            :param="{index: index, col: data.row.col}" />
                          <div style="max-width: 70px;margin: 0 auto;" @click.stop="editorWidth(index)">
                            <div class="item-num">{{index + 1}}</div>
                            <div class="item-width">
                              {{showWidth(cl.config.width)}}
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="容器列表" name="2">
            <div class="grid-content bg-purple cols-list">
              <div class="empty-notice-n" v-if="!containerBoxArr">当前容器为空，请添加组件</div>
              <el-table v-loading="loading" v-else :data="containerBoxArr" height="314"
                @cell-mouse-enter="handleMouseEnter" @cell-mouse-leave="handleMouseOut">
                <el-table-column label="序号" width="60" align="center">
                  <template slot-scope="scope">
                    {{scope.$index + 1}}
                  </template>
                </el-table-column>
                <el-table-column label="ID" align="center">
                  <template slot-scope="scope">
                    {{scope.row._other._tmpId}}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center">
                  <template slot-scope="scope">
                    <i :class="{'icon':true, 'iconfont':true, 'icon-jiantouarrow499':true, 'displayNo':isFirst(scope.$index)}"
                      @click="clickUp(scope.$index, scope.row._other._tmpId)"></i>
                    <i :class="{'icon':true, 'iconfont':true, 'icon-jiantouarrow505':true, 'displayNo':isLast(scope.$index)}"
                      @click="clickDown(scope.$index, scope.row._other._tmpId)"></i>
                    <i class="el-icon-delete" @click="deleteCol(scope.row._other._tmpId)"></i>
                  </template>
                </el-table-column>
              </el-table>
              <div class="add-btn">
                <el-button @click="addCol" type="success" size="small">添加</el-button>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </SetDesignDialog>
    <DialogAddContainerFormBox ref="addContainerFormBox" :tmpContainerColId="containerData._other._tmpId"
      :updateBjContainerBox="updateBjContainerBox" />
  </div>
</template>

<script>
import SetDesignDialog from '@/components/common/dialog/SetDesignDialog.vue'
import WDialogMoveLine from '@/components/common/design/dialog/widgets/WDialogMoveLine.vue'
import DialogAddContainerFormBox from '@/components/common/design/dialog/DialogAddContainerFormBox.vue'
import PaddingTop from '@/components/common/design/dialog/component/formitem/PaddingTop.vue'
import PaddingBottom from '@/components/common/design/dialog/component/formitem/PaddingBottom.vue'
import * as WindowType from '@/config/windowtype.js'
// import * as PubsubType from '@/config/pubsubtype.js'
import VueFunctions from '@/core/VueFunctions.js'
import BackendjsFunctions from '@/core/BackendjsFunctions.js'
import { mapState } from 'vuex'
// import PubSub from 'pubsub-js'
import _ from 'lodash'
export default {
  computed: {
    ...mapState([
      'design'
    ]),
    total () {
      let total = 0
      this.data.row.col.forEach(element => {
        total += parseInt(parseFloat(element.config.width).toFixed(2).replace('.', ''))
      })
      return total
    },
    isFirst () {
      return function (index) {
        if (index === 0) {
          return true
        } else {
          return false
        }
      }
    },
    isLast () {
      return function (index) {
        let len = this.containerBoxArr.length
        if (index === (len - 1)) {
          return true
        } else {
          return false
        }
      }
    }
  },
  created () {
    /*
    *** containerData：栅格信息
    *** containerBoxArr：栅格内容器数组
    */
    VueFunctions.method(WindowType.EDIT_CONTAINER_FORM_COL, (containerData, containerBoxArr) => {
      this.dialogShow = true
      this.containerData = containerData
      this.data = containerData.render.data
      this.containerBoxArr = containerBoxArr
      if (!this.data.type) {
        this.data.type = 'col-sm'
      }
      if (this.data.row.col && this.data.row.col.length === 1 && !this.data.row.col[0].config.width) {
        this.data.row.col[0].config.width = '100%'
      }
      if (this.$refs['settingDialog']) {
        this.$refs['settingDialog'].open()
      }
    })
  },
  mounted () {
    // PubSub.subscribe(PubsubType.PUBSUB_DIGLOG_COMPONENT_AND_CONTAINER_CLOSE, (event, data) => {
    //   this.close()
    // })
  },
  data () {
    return {
      currentWidth: '',
      dialogShow: false,
      loading: false,
      formLabelWidth: '120px',
      name: '栅格',
      activeName: '1',
      hasfooter: true,
      containerData: null,
      data: null,
      containerBoxArr: null,
      stepOffset: '0.8',
      renderSetTimeout: -1,
      renderSetTimeoutData: null
    }
  },
  watch: {
  },
  methods: {
    // 标签切换触发
    handleClick (tab, event) {
      if (tab.name === '2') {
        this.hasfooter = false
      } else {
        this.hasfooter = true
      }
    },
    moving (param) {
      let { index, lvalue, rvalue } = param
      let data = JSON.parse(JSON.stringify(this.data))
      data.row.col[index - 1].config.width = lvalue + '%'
      data.row.col[index].config.width = rvalue + '%'
      this.data = data
    },
    editorWidth (index) {
      let item = this.data.row.col[index]
      if (!item) {
        return
      }
      let width = parseInt(parseFloat(item.config.width).toFixed(2).replace('.', ''))
      this.$prompt('输入宽度！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: '' + width,
        inputPattern: /\d+/,
        inputErrorMessage: '输入正确的数字',
        closeOnClickModal: false
      }).then(({ value }) => {
        if (value > 10000) {
          this.$message.error('不能大于10000！')
          return
        }
        item.config.width = (value / 100).toFixed(2) + '%'
        let col = JSON.parse(JSON.stringify(this.data.row.col))
        let row = JSON.parse(JSON.stringify(this.data.row))
        let data = JSON.parse(JSON.stringify(this.data))
        row.col = col
        data.row = row
        this.data = data
      }).catch(() => {

      })
    },
    // 正常显示宽度
    showWidth (width) {
      return parseInt(parseFloat(width).toFixed(2).replace('.', ''))
    },
    // 平均分配
    argev () {
      if (!this.data || !this.data.row || !this.data.row.col || !this.data.row.col.length) {
        return
      }
      let len = parseInt(10000 / this.data.row.col.length)
      let lTotal = this.data.row.col.length * len
      let sub = 10000 - lTotal
      let tolsub = sub
      let tol = 0
      this.data.row.col.forEach((element, index) => {
        if (tolsub > 0) {
          tolsub--
          tol = tol + (len + 1)
        } else {
          tol = tol + len
        }
      })
      if (tol > 10000) {
        console.error('tol 大于 10000 ！')
        return
      }
      this.data.row.col.forEach((element, index) => {
        if (sub > 0) {
          sub--
          element.config.width = ((len + 1) / 100).toFixed(2) + '%'
        } else {
          element.config.width = (len / 100).toFixed(2) + '%'
        }
      })
    },
    clickUp (index, tmpId) {
      if (!this.isFirst(index)) {
        let arrId = []
        this.containerBoxArr.forEach(el => {
          arrId.push(el._other._tmpId)
        })
        if (arrId.indexOf(tmpId) > -1) {
          let filterArr = this.containerBoxArr.splice(arrId.indexOf(tmpId), 1)
          this.containerBoxArr.splice(arrId.indexOf(tmpId) - 1, 0, filterArr[0])
          BackendjsFunctions.sortContainerFormbox(_.cloneDeep(this.containerBoxArr))
        }
      }
    },
    clickDown (index, tmpId) {
      if (!this.isLast(index)) {
        let arrId = []
        this.containerBoxArr.forEach(el => {
          arrId.push(el._other._tmpId)
        })
        if (arrId.indexOf(tmpId) > -1) {
          let filterArr = this.containerBoxArr.splice(arrId.indexOf(tmpId), 1)
          this.containerBoxArr.splice(arrId.indexOf(tmpId) + 1, 0, filterArr[0])
          BackendjsFunctions.sortContainerFormbox(_.cloneDeep(this.containerBoxArr))
        }
      }
    },
    deleteCol (tmpId) {
      let isDelete = BackendjsFunctions.isDelContainerFormColBox(tmpId)
      if (isDelete) {
        let fellbackdata = _.cloneDeep(BackendjsFunctions.delContainerFormbox(tmpId))
        this.containerBoxArr = _.cloneDeep(fellbackdata.formbox)
        this.data.row.col = _.cloneDeep(fellbackdata.formcol.render.data.row.col)
      } else {
        this.$message.error('最后一个空容器不能删除！')
      }
    },
    addCol () {
      this.$refs['addContainerFormBox'].show()
    },
    updateBjContainerBox (box, col) {
      this.containerBoxArr = box
      this.data.row.col = col
    },
    handleMouseEnter (row, column, cell, event) {
      BackendjsFunctions.showShadowFormContainer(row._other._tmpId)
      BackendjsFunctions.scrollFormContainer(row._other._tmpId)
    },
    handleMouseOut (row, column, cell, event) {
      let hasTmpId = this.containerBoxArr.filter(item => {
        return item._other._tmpId === row._other._tmpId
      })
      if (hasTmpId.length > 0) {
        BackendjsFunctions.hideShadowFormContainer(row._other._tmpId)
      }
    },
    close () {
      this.dialogShow = false
      this.name = '栅格'
      this.activeName = '1'
      this.hasfooter = true
      this.containerData = null
      this.data = null
      this.stepOffset = '0.8'
      this.renderSetTimeout = -1
      this.renderSetTimeoutData = null
    },
    saveclose () {
      if (this.total - 10000 > 0) {
        this.$message.error('总宽度不能大于 10000 ！')
        return
      }
      this.containerData.render.data = _.cloneDeep(this.data)
      BackendjsFunctions.setContainerFormcol(this.containerData)
      this.close()
    }
  },
  components: {
    SetDesignDialog,
    WDialogMoveLine,
    DialogAddContainerFormBox,
    PaddingTop,
    PaddingBottom
  }
}

</script>
<style scoped lang="scss">
.edit-container-u {
  width: 840px;
  min-height: 350px;
}
.boxs {
  display: flex;
  flex-flow: row;
  margin-bottom: 24px;
  .item {
    min-width: 21px;
    min-height: 60px;
    border-left: 1px solid #a1a1a1;
    &:last-child {
      border-right: 1px solid #a1a1a1;
    }
    .item-width {
      text-align: center;
      font-size: 11px;
      color: #636363;
      margin-top: 4px;
      cursor: pointer;
    }
    .item-num {
      text-align: center;
      font-size: 11px;
      margin-top: 20px;
    }
  }
}
.edit-container-col .col-opt {
  display: flex;
  flex-flow: row-reverse;
}
.add-btn {
  margin-top: 20px;
  text-align: right;
}
.cols-list {
  /deep/ table th {
    color: #555;
    font-weight: normal;
  }
  i {
    font-size: 18px;
    cursor: pointer;
    margin: 0 3px;
    &.iconfont {
      font-size: 20px;
    }
    &:hover {
      color: #258ffb;
    }
  }
  .displayNo {
    color: #888888;
    cursor: not-allowed;
    opacity: 0.5;
    &:hover {
      color: #888888;
    }
  }
}
.radio-disblock {
  padding-top: 5px;
  padding-bottom: 10px;

  /deep/ .el-radio {
    line-height: 30px;
    min-width: 40%;
  }
}
</style>
